/**
 *
 * PathBrain.brain( xo );
 * ...
 * xo.goal( {x:18,y:343} );
 *
 */
var PathBrain = function( sprite, map ) {

	this.goal = function( pos ) {
		this.setPath( 
			this.getMap().astar(
				  this.getSprite().getPosition().getX()
				, this.getSprite().getPosition().getY()
				, pos.x
				, pos.y
			)
			, pos.x % this.getMap().getTileSize()
			, pos.y % this.getMap().getTileSize()
		);
	};

	this.clear = function() {
		this.setPath( [] );
	};

	//////////

	this.run = function( t ) {
		if ( this.getPath() && 0 != this.getPath().length ) {
			var goal = this.getPath()[ 0 ];
			var i = this.getMap().mapCoord( goal.getY() );
			var j = this.getMap().mapCoord( goal.getX() );
			
			if ( this.getSprite().towards( goal ) ) {
				this.getSprite().move();
			} else {
				this.getPath().shift();
				this.run( t );
			}
			if ( 0 == this.getPath().length ) {
				this.setPath( false );
			}
		}
		return true; /* still running */
	};

	this.convertPath = function( path, exo, eyo ) {
		var nuPath = [];
		var xo = this.getSprite().getPosition().getX() % this.getMap().getTileSize();
		var yo = this.getSprite().getPosition().getY() % this.getMap().getTileSize();
		for ( var i = ( 1 == path.length ) ? 0 : 1 ; i < path.length ; i++ ) {
			var goal = path[ i ];
			if ( i == path.length - 1 ) {
				xo = exo;
				yo = eyo;
			}
			nuPath.push( 
				new Point2d( 
					  goal.j * this.getMap().getTileSize() + xo 
					, goal.i * this.getMap().getTileSize() + yo
				)
			);

		}
		return nuPath;
	};

	this.setPath = function( path, exo, eyo ) {
		this.path_ = this.convertPath( path, exo, eyo );
	};

	this.getPath = function() {
		return this.path_;
	};


	//////////

	this.setSprite = function( sprite ) {
		this.sprite_ = sprite;
	};

	this.getSprite = function() {
		return this.sprite_;
	};

	this.setMap = function( map ) {
		this.map_ = map;
	};

	this.getMap = function() {
		return this.map_;
	};

	this.init = function( sprite, map ) {
		this.setMap( map );
		this.setSprite( sprite );
	};

	this.init( sprite, map );

};
	PathBrain.brain = function( xo ) {
		xo.setBrain(
			new PathBrain( xo.getSprite() , xo.getMap() )
		);
	};

